package com.smartEdu.module.schedule;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.smartEdu.module.schedule.GobalConstant;
import com.smartEdu.utils.IOUtils;
import com.smartEdu.utils.JsonUtil;
import com.smartEdu.vo.ScheduleEntityVo;

public class CourseInquiry {
	private String queryStucourseUrl = GobalConstant.QUERY_STU_COURSE_URL;
	private String queryClasscourseUrl = GobalConstant.QUERY_CLASS_COURSE_URL;
	private ArrayList<ScheduleEntityVo> scheduleEntityVos = new ArrayList<>();
	private int startYear;//学年开始年
	private int endYear;//学年结束年
	private int semester;//学期

	public ArrayList<ScheduleEntityVo> queryStuCourse(String xnxqid01) throws UnsupportedOperationException, IOException{  	//xn代表学年，xq代表学期
		String[] semesters = xnxqid01.split("-");
		startYear = Integer.valueOf(semesters[0]);
		endYear = Integer.valueOf(semesters[1]);
		semester = Integer.valueOf(semesters[2]);
		CloseableHttpClient client = HttpClients.createDefault();
		//建立Post对象
		HttpPost queryStuCoursePost = new HttpPost(queryStucourseUrl);
		//把Cookie传给头信息
		queryStuCoursePost.setHeader("Cookie",Login.Cookie);
		//建立一个NameValuePair数组，用于存储欲传送的参数
		List<NameValuePair> stuCoursePair = new ArrayList<NameValuePair>();
		//添加参数
		stuCoursePair.add(new BasicNameValuePair("xnxq01id",xnxqid01));
		stuCoursePair.add(new BasicNameValuePair("cj0701id",""));
		stuCoursePair.add(new BasicNameValuePair("zc",""));
		stuCoursePair.add(new BasicNameValuePair("demo",""));
		stuCoursePair.add(new BasicNameValuePair("sfFD","1"));
		
		//设置所传参数
		UrlEncodedFormEntity entitySource = new UrlEncodedFormEntity(stuCoursePair);
		queryStuCoursePost.setEntity(entitySource);
		//发送Post,并返回一个HttpResponse对象
		HttpResponse responseStuCourse = client.execute(queryStuCoursePost);
		String html = IOUtils.getHtml(responseStuCourse.getEntity().getContent(),"utf-8");
//		System.err.println(html);
		Document docCourse = Jsoup.parse(html);
		Elements eleCourse = docCourse.getElementsByTag("tbody").select("tr").select("td").select("div");

//		JSONObject json = new JSONObject();//课表
		try {
//			JSONObject elems = new JSONObject();
			for(int i = 1; i < 14; i += 2){//一周的课程
				JSONObject elem = new JSONObject();//一天的课
				for(int j = 0; j < 7; ++j){//一天的课程
					String str = eleCourse.get(i+j*14).html();
					str = str.replaceAll("&nbsp;", "");
					String[] courseArray = str.split("---------------------");
//					System.out.println(courseArray[0].length());
					elem.put("第"+(j*2+1)+"-"+(j*2+2)+"节", str);
					int t = i/2 + 1;
					
					if (!"".equals(str)) {
//						System.out.println(i+":"+j+"::"+courseArray.length);
						splitCourseInfo(courseArray, j*2+1, j*2+2, (i+1)/2);
					}
//					System.out.print("第"+(j*2+1)+"-"+(j*2+2)+"节"+" ");
				}
//				System.out.println("");
//				String strDay = getWeekend((i+1)/2);//星期几
//				elems.put(strDay, elem);
			}
//			json.put("schedule", elems);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println(json.toString());
//		获取所得信息测试		
//		try {
//			System.out.println(json.getJSONObject("schedule").getJSONObject("Saturday"));
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
		client.close();
		return scheduleEntityVos;
	}
	
	private String[] weekend = {"","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
	private String getWeekend(int idx){
		if(idx < 1 || 7 < idx){
			System.out.println("idx error");
			return "error";
		}
		return weekend[idx];
	}
	
	private void splitCourseInfo(String[] courses, int startSection, int endSection, int dayofweek) throws CloneNotSupportedException {
		for(int i=0;i<courses.length;i++) {
			ScheduleEntityVo vo = new ScheduleEntityVo();
			courses[i] = courses[i].replaceAll("<(/)?font.*?>", "");
			courses[i] = courses[i].replaceAll("\n", "");
			if (i!=0) {
				courses[i] = courses[i].substring(4);
			}
//			System.err.println(courses[i]);
			String[] entity = courses[i].split("<br>");
			String end = String.valueOf(endSection);
			if ( -1 != entity[3].indexOf(end)) {
				vo.setEndSection(endSection);
			}
			else {
				vo.setEndSection(endSection-1);
			}
			vo.setStartSection(startSection);
			vo.setStartYear(startYear);
			vo.setEndYear(endYear);
			vo.setSemester(semester);
			vo.setCourseName(entity[0]);
			vo.setTeacher(entity[1]);
			vo.setClasssroom(entity[4]);
			vo.setDayOfWeek(dayofweek);
			Pattern p = Pattern.compile("^.*?\\((.?)周\\)");
			Matcher matcher = p.matcher(entity[2]);
			matcher.matches();
			switch(matcher.group(1)) {
				case "":
					vo.setEveryWeek(0);
					break;
				case "单":
					vo.setEveryWeek(1);
					break;
				case "双":
					vo.setEveryWeek(2);
					break;
			}
			entity[2] = entity[2].replaceAll("\\(.*?\\)", "");
			String[] as = entity[2].split(",");
			for (String s : as) {
				ScheduleEntityVo vot = (ScheduleEntityVo) vo.clone();
//				s.replaceAll("\r", "");
//				s = s.substring(1);
				String[] sArray = s.split("-");
				vot.setStartWeek(Integer.valueOf(sArray[0]));
				if (sArray.length > 1) {
					vot.setEndWeek(Integer.valueOf(sArray[1]));
				}
				else {
					vot.setEndWeek(Integer.valueOf(sArray[0]));
				}
				scheduleEntityVos.add(vot);
			}
		}
	}
	
	public static void main(String[] args) {
//		String s = "JavaEE框架开发实训<br><font title=\"老师\">赵卓君</font><br><font title=\"周次(节次)\">7-10(周)<br>[01-02-03-04节]</font><br><font title=\"教室\">ZA204</font><br>---------------------<br>JavaEE框架开发实训<br><font title=\"老师\">赵卓君</font><br><font title=\"周次(节次)\">1-3(周)<br>[01-02-03-04节]</font><br><font title=\"教室\">ZA204</font><br>---------------------<br>JavaEE框架开发实训<br><font title=\"老师\">张晓燕</font><br><font title=\"周次(节次)\">14-16(周)<br>[01-02-03-04节]</font><br><font title=\"教室\">ZA204</font><br>---------------------<br>JavaEE框架开发实训<br><font title=\"老师\">赵卓君</font><br><font title=\"周次(节次)\">11,13(周)<br>[01-02-03-04节]</font><br><font title=\"教室\">ZA204</font><br>---------------------<br>JavaEE框架开发实训<br><font title=\"老师\">张申勇</font><br><font title=\"周次(节次)\">4-6(周)<br>[01-02-03-04节]</font><br><font title=\"教室\">ZA204</font><br>";
//		s = s.replaceAll("</?font.*?>", "");
//		System.err.println(s);
		String a = "1-17(周)";
		System.err.println(a.length());
//		String regWeek = "^.*?\\((.?)周\\)";
//		a = a.replaceAll("\\(.*?\\)", "");
//		System.err.println(a);
//		String reg = ""
//		System.err.println(a.replaceAll("^.*?\\(.*?\\)", ""));
		Pattern p = Pattern.compile("^.*?\\((.?)周\\)");
		Matcher matcher = p.matcher(a);
		matcher.matches();
		System.err.println(matcher.group(1));
	}
	
}
